package indi.yuluo.controller;

import com.alibaba.druid.support.json.JSONUtils;
import indi.yuluo.util.MD5Util;
import indi.yuluo.vo.Msg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: yuluo
 * @CreateTime: 2022-08-15  19:18
 * @Description: TODO
 */

@RestController
@Slf4j
@Api(value = "翻译接口")
@RequestMapping("/tran")
public class TranslateController {

    @PostMapping("/translate")
    @ApiOperation(value = "访问百度翻译api翻译题目", httpMethod = "POST", notes = "存在bug")
    public Msg translate(String content) {

        boolean flag = false;

        // 接受参数
        String data = content.replace(" ", "").replace("\n", "").replace("?", "");
        // log.info("接受的请求参数：{}", data);

        // 组装请求参数
        String api = "https://fanyi-api.baidu.com/api/trans/vip/translate";
        String appid = "20220815001308202";
        String securityKey = "09VsRbu0iEAzA90XAi23";
        String salt = getRandom();
        String from = "zh";
        String to = "en";
        String sign = MD5Util.getMD5(appid + data + salt + securityKey);

        // 设置post请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");

        // 设置请求体
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("q", data);
        multiValueMap.add("from", from);
        multiValueMap.add("to", to);
        multiValueMap.add("appid", appid);
        multiValueMap.add("salt", salt);
        multiValueMap.add("sign",sign);

        // 组合请求头和请求体
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(multiValueMap, requestHeaders);

        // 发起请求
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.postForObject(api, httpEntity, String.class);

        assert forObject != null;
        Object result = JSONUtils.parse(forObject);

        // 解析结果
        // log.info("请求结果: {}", result);
        Pattern compile = Pattern.compile("dst=(.*?)\\.");
        Matcher matcher = compile.matcher(String.valueOf(result));

        String resData = "";
        while (matcher.find()) {
            resData = matcher.group();
        }

        if (Objects.nonNull(resData)) {
            flag = true;
        }

        // 返回数据
        return flag ? Msg.success().add("data_success", resData) : Msg.fail().add("data_error", "接口异常，处理失败！");
    }

    /**
     * 生成10位随机数
     * @return
     */
    public static String getRandom() {

        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < 10; i ++) {
            stringBuilder.append(random.nextInt(10));
        }

        return stringBuilder.toString();
    }

}
